package com.selebash.ast;

import com.selebash.exception.SelebashException;
import com.selebash.runtime.ExecutionContext;
import java.util.ArrayList;
import java.util.List;

/**
 * @author sad
 */
public class IfAst extends SequenceAst {

    private final List<AbstractAst> conditionList = new ArrayList<>();
    private final List<AbstractAst> elseAstNodesQueue = new ArrayList<>();

    public List<AbstractAst> getCondition() {
        return conditionList;
    }

    public void addElseAstNodes(List<AbstractAst> nodes) {
        elseAstNodesQueue.addAll(nodes);
    }

    public void addCondition(AbstractAst ast) {
        conditionList.add(ast);
    }

    private boolean isResultTrue(Object result) {
        if (result == null) {
            return false;
        }

        if (result instanceof Boolean) {
            return (Boolean) result;
        }

        if (result instanceof String) {
            String str = (String) result;
            str = str.trim();
            return !str.isEmpty();
        }

        if (result instanceof Integer) {
            Integer value = (Integer) result;
            return value != 0;
        }

        return false;
    }

    @Override
    public void process(ExecutionContext executionContext) {
        boolean ifresult = true;
        for (AbstractAst condition : conditionList) {
            boolean isFalseWithException = false;
            try {
                condition.process(executionContext);
            } catch (SelebashException ex) {
                isFalseWithException = true;
            }
            boolean isResultTrue = isResultTrue(executionContext.getLastResult());
            boolean result = !isFalseWithException && isResultTrue;
            if (!result) {
                ifresult = false;
                break;
            }
        }

        if (ifresult) {
            runSequenceElements(executionContext, getNested(), null);
        } else {
            if (elseAstNodesQueue != null && !elseAstNodesQueue.isEmpty()) {
                runSequenceElements(executionContext, elseAstNodesQueue, null);
            }
        }
    }
}
